package com.kehutong.department.service;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.DateUtil;
import com.kehutong.department.entity.ThirdEmployee;
import com.kehutong.department.entity.ThirdEnterpriseConfig;
import com.kehutong.wwin.service.util.WwInHttpClient;
import com.tencentcloudapi.common.CommonClient;
import org.coraframework.bean.Beans;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.List;

@WebService("/basic/MessagePush/service")
public class MessagePushService {
    private static final Logger logger = LoggerFactory.getLogger(MessagePushService.class);
    @Inject
    private DoveClient doveClient;
    @Inject
    private WwInHttpClient wwInHttpClient;

    @Inject
    private CommonClient commonClient;

    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/ThirdMessagePush")
    public Object ThirdMessagePush(JSONObject json) throws Exception {
        String time = DateUtil.getTime(DateUtil.YEAR_MONTH_DAY_HOUR_MINUTE_SECONDS);
        final String companyNo = json.getString("companyNo");
        final String  msgtype = json.getString("msgtype");
        final String  uId = json.getString("userId");
        final String  wechatName = json.getString("wechatName");
        final String  content = json.getString("content");
        final String  url = json.getString("url");
        StringBuilder sb5 = new StringBuilder();
        sb5.append(wechatName).append("于").append(time).append(content);
        try {
            if (Objects.isEmpty(uId)) {
                String userId = getUserId(json.getString("userId"), companyNo);
                if (Objects.isEmpty(userId))
                    return Result.error(0, "找不到userId");
                json.put("userId", userId);
            }

            JSONObject agentJson = doveClient.post("/kht-bin/wwout/agent/get", http -> {
                http.addParam("companyNo", companyNo);
            });
            if (agentJson.getIntValue("code") != 200) {
                return Result.error(0, agentJson.getString("message"));
            }
            JSONObject data = agentJson.getJSONObject("data");
            String access_token = data.getString("access_token");
            String agentid = data.getString("agentid");
            wwInHttpClient.post("/cgi-bin/message/send", http -> {
                http.addParam("access_token", access_token);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("touser", uId);
                jsonObject.put("msgtype",msgtype);
                jsonObject.put("agentid", agentid);
                JSONObject cardText = new JSONObject();
                cardText.put("content", sb5.toString()+"\n"+"<a href=\""+url+"\">详情</a>");
                jsonObject.put("text", cardText);
                http.setBody(jsonObject.toJSONString());
            });

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.error(0, e.getMessage());
        }
        return null;
    }

    private String getUserId(String userId, String companyNo){
        try {
            JSONObject result = doveClient.post("/kht-bin/wwout/getEmployeeByUserId",(http)->{
                http.addParam("companyNo", companyNo);
                JSONObject body = new JSONObject();
                body.put("userId", userId);
                http.setBody(body.toJSONString());
            });

            if (result.getIntValue("code") == 200) {
                JSONObject jsonObject = result.getJSONObject("data");
                return jsonObject.getString("userId");
            } else {
                return null;
            }
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            return null;
        }

    }

    @ReqMapping("/ThirdMassPush")
    public void ThirdMassPush(JSONObject jsonObject) throws Exception {
        JSONArray residentIds = jsonObject.getJSONArray("residentIds");
        String thirdId =  jsonObject.getString("thirdId");
        //获取员工
        ThirdEmployee thirdEmployee = jdbcSession.findOne(ThirdEmployee.class).eq("thirdId",thirdId).exe();
        if(Objects.isNull(thirdEmployee)){
            throw new RuntimeException("未查到员工信息 "+thirdId);
        }
        //获取住户外部信息


       // JSONArray data = result.getJSONArray("data");


    }



}
